package com.ooqiu.gaming.ui.feedback;

import android.Manifest;
import android.app.Activity;
import android.content.DialogInterface;
import android.support.annotation.IntRange;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.miguelbcr.ui.rx_paparazzo2.RxPaparazzo;
import com.miguelbcr.ui.rx_paparazzo2.entities.FileData;
import com.miguelbcr.ui.rx_paparazzo2.entities.Response;
import com.miguelbcr.ui.rx_paparazzo2.entities.size.ScreenSize;
import com.miguelbcr.ui.rx_paparazzo2.entities.size.SmallSize;
import com.ooqiu.gaming.R;
import com.ooqiu.gaming.api.FileManager;
import com.ooqiu.gaming.components.glide.GlideApp;
import com.ooqiu.gaming.view.SquareImageView;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.ObservableSource;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.observers.DefaultObserver;
import io.reactivex.schedulers.Schedulers;


/**
 * Created by Eenie on 2017/6/2.
 * Email: eeniework@gmail.com
 * Des:
 */

public class UploadImgAdapter extends BaseMultiItemQuickAdapter<MultiItemEntity, BaseViewHolder> {
    MultiItemEntity emptyFlag;
    Activity mActivity;
    FileManager mFileManager;
    int maxCount;
    RxPermissions mRxPermissions;

    public UploadImgAdapter(Activity activity, FileManager manager, List<MultiItemEntity> data, int maxCount) {
        super(data);
        mActivity = activity;
        mFileManager = manager;
        mRxPermissions = new RxPermissions(activity);
        addItemType(0, R.layout.item_upload_img_empty);
        addItemType(1, R.layout.item_upload_img);
        this.maxCount = maxCount;

        getData().add(emptyFlag = new MultiItemEntity() {
            @Override
            public int getItemType() {
                return 0;
            }
        });
    }

    @Override
    protected void convert(final BaseViewHolder helper, MultiItemEntity item) {
        switch (item.getItemType()) {
            case 0:
                helper.getView(R.id.empty_layout).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showAlert();
                    }
                });
                break;
            case 1:
                UploadImg uploadImg = (UploadImg) item;
                SquareImageView iv = helper.getView(R.id.img_pic);
                GlideApp.with(mContext).load(uploadImg.getPath()).into(iv);
                break;
        }

    }


    public List<UploadImg> getImgs() {
        List<UploadImg> imgs = new ArrayList<>();
        for (MultiItemEntity multiItemEntity : getData()) {
            if (multiItemEntity.getItemType() == 1) {
                UploadImg uploadImg = (UploadImg) multiItemEntity;
                imgs.add(uploadImg);
            }
        }
        return imgs;
    }


    public void refresh() {
        if (getData().size() > maxCount) {
            getData().remove(getData().size() - 1);
        } else {
            if (getData().contains(emptyFlag)) {

            } else {
                getData().add(emptyFlag);
            }
        }
        notifyDataSetChanged();
    }


    @Override
    public void remove(@IntRange(from = 0L) int position) {
        mData.remove(position);
        if (getData().size() > maxCount) {
            getData().remove(getData().size() - 1);
        } else {
            if (getData().contains(emptyFlag)) {

            } else {
                getData().add(emptyFlag);
            }
        }
        int internalPosition = position + getHeaderLayoutCount();
        notifyItemRemoved(internalPosition);
        notifyItemRangeChanged(internalPosition, mData.size() - internalPosition);
    }


    private void showAlert() {
        new AlertDialog.Builder(mContext)
                .setItems(new String[]{"拍照", "相册"}, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                RxPaparazzo.single(mActivity)
                                        .useInternalStorage()
                                        .size(new SmallSize())
                                        .usingCamera()
                                        .subscribeOn(Schedulers.io())
                                        .flatMap(new Function<Response<Activity, FileData>, ObservableSource<UploadRes>>() {
                                            @Override
                                            public ObservableSource<UploadRes> apply(Response<Activity, FileData> fileData) throws Exception {
                                                if (fileData.resultCode() == Activity.RESULT_OK) {
                                                    return mFileManager.uploadImg(fileData.data().getFile().getAbsolutePath())
                                                            .subscribeOn(Schedulers.io());
                                                } else {
                                                    throw new IllegalStateException("取消上传");
                                                }
                                            }
                                        })
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .doOnNext(new Consumer<UploadRes>() {
                                            @Override
                                            public void accept(UploadRes uploadRes) throws Exception {
                                                getData().add(0, new UploadImg(uploadRes.getPath(), uploadRes.getName()));
                                                refresh();
                                            }
                                        })
                                        .compose(mRxPermissions.ensure(Manifest.permission.CAMERA))
                                        .subscribe(new DefaultObserver<Boolean>() {



                                            @Override
                                            public void onNext(Boolean aBoolean) {

                                            }

                                            @Override
                                            public void onError(Throwable e) {
                                                Toast.makeText(mActivity, e.getMessage(), Toast.LENGTH_SHORT).show();
                                                e.printStackTrace();
                                            }

                                            @Override
                                            public void onComplete() {

                                            }
                                        });


                                break;
                            case 1:
                                RxPaparazzo.single(mActivity)
                                        .useInternalStorage()
                                        .size(new ScreenSize())
                                        .usingGallery()
                                        .subscribeOn(Schedulers.io())
                                        .flatMap(new Function<Response<Activity, FileData>, ObservableSource<UploadRes>>() {
                                            @Override
                                            public ObservableSource<UploadRes> apply(Response<Activity, FileData> fileData) throws Exception {
                                                if (fileData.resultCode() == Activity.RESULT_OK) {
                                                    return mFileManager.uploadImg(fileData.data().getFile().getAbsolutePath())
                                                            .subscribeOn(Schedulers.io());
                                                } else {
                                                    throw new IllegalStateException("取消上传");
                                                }
                                            }
                                        })
                                        .observeOn(AndroidSchedulers.mainThread())
                                        .doOnNext(new Consumer<UploadRes>() {
                                            @Override
                                            public void accept(UploadRes uploadRes) throws Exception {
                                                getData().add(0, new UploadImg(uploadRes.getPath(), uploadRes.getName()));
                                                refresh();
                                            }
                                        })
                                        .subscribe(new DefaultObserver<UploadRes>() {

                                            @Override
                                            public void onNext(UploadRes uploadRes) {

                                            }

                                            @Override
                                            public void onError(Throwable e) {
                                                e.printStackTrace();
                                            }

                                            @Override
                                            public void onComplete() {

                                            }
                                        });


                                break;
                        }

                    }
                })
                .create()
                .show();
    }




}
